/*
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dailydev.wave.robot.servlet;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dailydev.wave.robot.IRobot;
import org.dailydev.wave.robot.RobotException;
import org.dailydev.wave.robot.serializer.CapabilitiesSerializer;
import org.dailydev.wave.robot.serializer.ISerializer;
import org.dailydev.wave.robot.serializer.ProfileSerializer;

import com.google.wave.api.ParticipantProfile;

/**
 * @author Roman Bosak, DailyDev.org
 */
public class ProfileServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = -2145522801768623854L;

    /**
     * {@link ProfileServlet}'s logger
     */
    private static Logger log = Logger.getLogger(ProfileServlet.class.getName());

    /**
     * Logger for request and response payload
     */
    private static Logger payloadLog = Logger.getLogger("robot.payload.events");

    protected IRobot robot;

    protected ISerializer<IRobot> capabilitiesGenerator = new CapabilitiesSerializer();

    private final ISerializer<ParticipantProfile> serializer = new ProfileSerializer();

    /** {@inheritDoc} */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ParticipantProfile profile = new ParticipantProfile(robot.getRobotName(), robot.getRobotAvatar(), req
                .getRequestURL().toString());

        try {
            String responseBody = serializer.serialize(profile);

            resp.setContentType("application/json");
            resp.setCharacterEncoding("utf-8");
            resp.getWriter().write(responseBody);

            if (payloadLog.isLoggable(Level.FINEST)) {
                payloadLog.finest("RESPONSE: 200 OK >>>" + responseBody + "<<<");
            }
        } catch (RobotException e) {
            log.log(Level.SEVERE, "500 - Internal Server Error", e);
            if (payloadLog.isLoggable(Level.FINEST)) {
                payloadLog.finest("RESPONSE: 500 Internal Server Error >>> " + e.getMessage());
            }
            resp.setStatus(500);
        }
    }

    /** {@inheritDoc} */
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        String robotFactoryClassName = config.getServletContext().getInitParameter(
                IRobotFactory.ROBOT_FACTORY__PARAM_NAME);
        try {
            Class<IRobotFactory> robotFactoryClass = (Class<IRobotFactory>) Class.forName(robotFactoryClassName);
            IRobotFactory robotFactory = robotFactoryClass.newInstance();
            robot = robotFactory.buildRobot(config);
        } catch (ClassNotFoundException e) {
            throw new ServletException("Unable to find robot factory class '" + robotFactoryClassName + "'", e);
        } catch (InstantiationException e) {
            throw new ServletException("Unable to instantiate robot factory class '" + robotFactoryClassName + "'", e);
        } catch (IllegalAccessException e) {
            throw new ServletException("Unable to instantiate robot factory class '" + robotFactoryClassName + "'", e);
        }
    }

}
